﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Models.NPOI;
using SHZY.DataEncryption;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SHZY.BaseData.Entitys.Dto.QmsBaseIpqccalendarworktime;
using SHZY.system.Entitys;
using SHZY.system.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SHZY.BaseData.Interfaces;
using SHZY.BaseData.Entitys;

namespace SHZY.BaseData;

/// <summary>
/// 业务实现：工作时间.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "QmsBaseIpqccalendarworktime", Order = 200)]
[Route("api/BaseData/[controller]")]
public class QmsBaseIpqccalendarworktimeService : IQmsBaseIpqccalendarworktimeService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBaseIpqccalendarworktimeEntity> _repository;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="QmsBaseIpqccalendarworktimeService"/>类型的新实例.
    /// </summary>
    public QmsBaseIpqccalendarworktimeService(
        ISqlSugarRepository<QmsBaseIpqccalendarworktimeEntity> qmsBaseIpqccalendarworktimeRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = qmsBaseIpqccalendarworktimeRepository;
        _dataInterfaceService = dataInterfaceService;
        _userManager = userManager;
    }

    /// <summary>
    /// 获取工作时间.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<QmsBaseIpqccalendarworktimeInfoOutput>();
    }

    /// <summary>
    /// 获取工作时间列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBaseIpqccalendarworktimeListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<QmsBaseIpqccalendarworktimeEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.year), it => it.Year.ToString().Contains(input.year))
            .WhereIF(!string.IsNullOrEmpty(input.name), it => it.Name.Contains(input.name))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.Year.ToString().Contains(input.keyword) || it.Name.Contains(input.keyword))
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id);

        if (!string.IsNullOrEmpty(input.sidx))
            queryable.OrderBy(input.sidx + " " + input.sort);

        var data = await queryable.Select(it => new QmsBaseIpqccalendarworktimeListOutput
        {
            id = it.Id,
            year = it.Year,
            name = it.Name,
            startTime = it.StartTime,
            endTime = it.EndTime,
            enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "无效", "有效"),
        }).ToPagedListAsync(input.currentPage, input.pageSize);

        return PageResult<QmsBaseIpqccalendarworktimeListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建工作时间.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] QmsBaseIpqccalendarworktimeCrInput input)
    {
        //if (await _repository.AnyAsync(x => (x.Year == input.year) && x.DeleteMark == null))
        //    throw Oops.Oh(ErrorCode.COM1004);
        var startAny = await _repository.Context.Queryable<QmsBaseIpqccalendarworktimeEntity>().Where(it => (SqlFunc.ToTime(input.startTime) >= SqlFunc.ToTime(it.StartTime) && SqlFunc.ToTime(input.startTime) <= SqlFunc.ToTime(it.EndTime)) && it.Year == input.year).AnyAsync();
        var endAny = await _repository.Context.Queryable<QmsBaseIpqccalendarworktimeEntity>().Where(it => (SqlFunc.ToTime(input.endTime) >= SqlFunc.ToTime(it.StartTime) && SqlFunc.ToTime(input.endTime) <= SqlFunc.ToTime(it.EndTime)) && it.Year == input.year).AnyAsync();
        if(startAny || endAny)
             throw Oops.Oh("当前设置时间区间重叠!");
        var entity = input.Adapt<QmsBaseIpqccalendarworktimeEntity>();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator())
             .CallEntityMethod(m => m.LastModify()).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 获取工作时间无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    private async Task<dynamic> GetNoPagingList([FromQuery] QmsBaseIpqccalendarworktimeListQueryInput input)
    {
        return await _repository.Context.Queryable<QmsBaseIpqccalendarworktimeEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.year), it => it.Year.ToString().Contains(input.year))
            .WhereIF(!string.IsNullOrEmpty(input.name), it => it.Name.Contains(input.name))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.Year.ToString().Contains(input.keyword) || it.Name.Contains(input.keyword))
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
            .Select(it => new QmsBaseIpqccalendarworktimeListOutput
            {
                id = it.Id,
                year = it.Year,
                name = it.Name,
                startTime = it.StartTime,
                endTime = it.EndTime,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "无效", "有效"),
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToListAsync();
    }

    /// <summary>
    /// 导出工作时间.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] QmsBaseIpqccalendarworktimeListQueryInput input)
    {
        var exportData = new List<QmsBaseIpqccalendarworktimeListOutput>();
        if (input.dataType == 0)
            exportData = Clay.Object(await GetList(input)).Solidify<PageResult<QmsBaseIpqccalendarworktimeListOutput>>().list;
        else
            exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"名称\",\"field\":\"name\"},{\"value\":\"年度\",\"field\":\"year\"},{\"value\":\"开始时间\",\"field\":\"startTime\"},{\"value\":\"结束时间\",\"field\":\"endTime\"},{\"value\":\"有效标志\",\"field\":\"enabledMark\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "工作时间.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
        }

        var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
        ExcelExportHelper<QmsBaseIpqccalendarworktimeListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 更新工作时间.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] QmsBaseIpqccalendarworktimeUpInput input)
    {
        var entity = input.Adapt<QmsBaseIpqccalendarworktimeEntity>();
        var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
        {
            it.Year,
            it.Name,
            it.StartTime,
            it.EndTime,
            it.EnabledMark,
        }).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除工作时间.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Deleteable<QmsBaseIpqccalendarworktimeEntity>().Where(it => it.Id.Equals(id)).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1002);
    }
}